package com.aaa.filter;

import com.aaa.util.JwtUtils;
import com.aaa.vo.ActivierUser;
import com.aaa.vo.R;
import com.alibaba.fastjson.JSON;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@ConfigurationProperties(prefix = "anon")
@Data
public class LoginFilter implements GlobalFilter, Ordered{

    @Autowired
    private StringRedisTemplate redisTemplate;

    private List<String> urls;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //1.获取请求路径
        String path = request.getPath().toString();
        //2.判断该路径是否为login
        if(path!=null && path.contains("/system/user/login")){
            return chain.filter(exchange);//放行
        }
        //3.获取token
        String token = request.getHeaders().getFirst("token");
        //4.检验token 并解析
        if(!JwtUtils.checkToken(token)){
            return result(response,20002,"未登录");
        }
        //5. 判断当前请求路径是否是放行。
        /*String[] split = path.split("/");
        String path1="/"+split[1]+"/"+split[2];

        if(urls.contains(path1)){
            return chain.filter(exchange);
        }

        Long userId= JwtUtils.getMemberIdByJwtToken(token);
        //5.判断当前用户得权限。
        String s = redisTemplate.opsForValue().get("user::" + userId);
        ActivierUser activierUser= JSON.parseObject(s,ActivierUser.class);

        if(activierUser.getPermissions().contains(path)){
            return chain.filter(exchange);
        }else{
            return result(response,20003,"未授权");
        }*/
        return chain.filter(exchange);
    }

    private Mono<Void> result(ServerHttpResponse response,Integer code,String msg){
        try {
            byte[] datas = JSON.toJSONString(R.error().code(code).message(msg)).getBytes("utf-8");
            DataBuffer buffer = response.bufferFactory().wrap(datas);
            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffer));
        }catch (Exception e){
            throw new RuntimeException("");
        }
    }
    @Override
    public int getOrder() {
        return 0;
    }
}
